import { useState, useEffect, useMemo } from "react";
import { MarkerPosition } from "./index";
import { getAnomalyType } from "../../constants";
import { BarItem } from "../BarMarker";
import { getPosition } from "@/utils/position";

// 柱子数据
const allBars: BarItem[] = [
  {
    id: "bar1",
    position: { x: 35.7, y: 13, width: 4, height: 58 },
  },
  {
    id: "bar2",
    position: { x: 44.6, y: 17, width: 4, height: 55 },
  },
  {
    id: "bar3",
    position: { x: 52.3, y: 21, width: 4, height: 51 },
  },
  {
    id: "bar4",
    position: { x: 59.5, y: 24, width: 4, height: 48 },
  },
  {
    id: "bar5",
    position: { x: 65.7, y: 27.8, width: 4, height: 42 },
  },
];

interface MarkerHookProps {
  trendData: any[];
  currentKey: string | undefined;
  currentDevice: string | undefined;
  currentPathDevice: string | undefined;
  viewportSize: {
    width: number;
    height: number;
  };
}

const useMarker = ({
  trendData,
  currentKey,
  currentDevice,
  currentPathDevice,
  viewportSize,
}: MarkerHookProps) => {
  // 添加当前显示的标记点索引状态
  const [currentMarkerIndex, setCurrentMarkerIndex] = useState(0);

  // 根据trendData生成标记点数据
  const trendMarkers = useMemo(() => {
    if (!trendData || trendData.length === 0) {
      return [];
    }

    // 为每个趋势数据项生成随机位置和类型
    return trendData.map((item, index) => {
      // 生成随机位置，确保分布在屏幕合理范围内
      return {
        id: `trend-${index}`,
        title: item.tagDesc || item.evaluationItemName,
        value:
          item.values && item.values.length > 0
            ? item.values[item.values.length - 1].toString()
            : "",
        description: item.abnormalCause || "",
        predictTime: item.predictTime || "",
        type: getAnomalyType(item.currentState),
        position: getPosition(item.tagDesc || item.evaluationItemName),
        updateTime:
          item.times && item.times.length > 0
            ? item.times[item.times.length - 1]
            : new Date().toISOString(),
      };
    });
  }, [trendData, currentKey]);

  // 添加轮播效果的useEffect
  useEffect(() => {
    if (currentKey === "question" && trendMarkers.length > 0) {
      const intervalId = setInterval(() => {
        setCurrentMarkerIndex((prevIndex) =>
          prevIndex >= trendMarkers.length - 1 ? 0 : prevIndex + 1
        );
      }, 5000); // 每5秒切换一次

      return () => clearInterval(intervalId); // 清理定时器
    }
  }, [trendMarkers, currentKey]);

  // 计算标记点的实际像素位置
  const getMarkerPixelPosition = (position: MarkerPosition) => {
    const { x: percentX, y: percentY } = position;
    const { width, height } = viewportSize;

    return {
      x: width * (percentX / 100),
      y: height * (percentY / 100),
    };
  };

  // 计算操作优化点
  const getConfirmedMarkerPixelPosition = (index:number) => {
    console.log("index", index);
    const { width, height } = viewportSize;
    const result = [
      {
        x: width * (38 / 100),
        y: height * (60 / 100),
      },
      {
        x: width * (47 / 100),
        y: height * (60 / 100),
      },
      {
        x: width * (55 / 100),
        y: height * (60 / 100),
      },
      {
        x: width * (62 / 100),
        y: height * (60 / 100),
      },
      {
        x: width * (68 / 100),
        y: height * (60 / 100),
      },
    ];
    return result[index];
  };

  // 获取当前应该显示的标记点
  const currentMarker = useMemo(() => {
    if (trendMarkers.length === 0) {
      return null;
    }
    return trendMarkers[currentMarkerIndex];
  }, [currentKey, trendMarkers, currentMarkerIndex]);

  // 根据 cDevice 获取显示的柱子
  const getBars = useMemo((): BarItem[] => {
    let cDevice:any="";
    if(currentKey==='param'){
      cDevice = currentDevice;
    } else if(currentKey==='path'){
      cDevice = currentPathDevice;
    }
    // 如果是 "all" 或者没有指定，显示所有柱子
    if (!cDevice || cDevice === "all" || cDevice === "全部" ) {
      return allBars;
    }

    // 尝试将 cDevice 转换为数字
    const deviceIndex = parseInt(cDevice as string, 10);

    // 如果不是有效数字，或者超出范围，返回空数组
    if (isNaN(deviceIndex) || deviceIndex < 1 || deviceIndex > allBars.length) {
      return [];
    }

    // 返回对应索引的柱子（数组索引从0开始，而设备索引从1开始）
    return [allBars[deviceIndex - 1]];
  }, [currentDevice, currentPathDevice,currentKey]);

  return {
    trendMarkers,
    currentMarker,
    getMarkerPixelPosition,
    getConfirmedMarkerPixelPosition,
    getBars,
  };
};

export default useMarker;
